package com.zx.scp.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jd.jr.pay.gate.signature.util.JdPayUtil;
import com.zx.jd.model.AsynNotifyResponse;
import com.zx.jd.model.PayTradeVo;
import com.zx.jd.util.PropertyUtils;
import com.zx.map.service.domain.nocard.NocardCallBackDomain;
import com.zx.map.service.domain.nocard.NocardPayReturnDomain;
import com.zx.scp.service.NoCardIncomeService;

/**
 * 京东无卡支付
 *
 * @author jefferry
 */
@Controller
@RequestMapping("/jdnocard")
public class JdNocardPayController {

    /**
     * log
     */
    private static Logger log = Logger.getLogger(JdNocardPayController.class);
    @Autowired
    private NoCardIncomeService noCardIncomeService;

    /**
     * 无卡收款
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/nocardCallBack")
    @ResponseBody
    public String nocardCallBack(NocardCallBackDomain nocardCallBackDomain,
                                 Model model, HttpServletRequest request, HttpServletResponse response) {
    	StringBuilder sb = new StringBuilder();
    	try {
        	
    		try {
    			BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
    			String line = null;

    			while ((line = br.readLine()) != null) {
    				sb.append(line);
    			}
    			log.info("异步通知原始数据:" + sb);
    		} catch (IOException e) {
    			log.error("异步通知原始数据异常:" + e);
    			return "fail";
    		}

    		String deskey = PropertyUtils.getProperty("wepay.merchant.desKey");
    		String pubKey = PropertyUtils.getProperty("wepay.jd.rsaPublicKey");
    		try {
    			System.out.println("异步通知解析数据开始:");
    			AsynNotifyResponse anRes = JdPayUtil.parseResp(pubKey, deskey, sb.toString(), AsynNotifyResponse.class);
    			System.out.println("异步通知解析数据结束:" + anRes);
    			log.info("异步通知订单号：" + anRes.getTradeNum() + ",状态：" + anRes.getStatus() + "成功!!!!");

    			NocardPayReturnDomain nocardPayReturnDomain = new NocardPayReturnDomain();
                nocardPayReturnDomain.setOrderId(anRes.getTradeNum());
                String amount = new BigDecimal(anRes.getAmount()).divide(
                        new BigDecimal("100")).toString();
                nocardPayReturnDomain.setAmount(amount);
                List<PayTradeVo> payList = anRes.getPayList();
                if(payList!=null&&payList.size()>0){
                	PayTradeVo payTradeVo = payList.get(0);
                	String cardNo = payTradeVo.getDetail().getCardNo();
                	if(StringUtils.isNotEmpty(cardNo)){
                		nocardPayReturnDomain.setLastNo(cardNo.substring(cardNo.length()-4, cardNo.length()));
                	}
                	nocardPayReturnDomain.setBankCode(payTradeVo.getDetail().getBankCode());
                	//nocardPayReturnDomain.setBank(bank);
                	nocardPayReturnDomain.setCardType("0"+payTradeVo.getDetail().getCardType());
                }
                nocardPayReturnDomain.setStatus("2".equals(anRes.getStatus()) ? "S" : "F");
                nocardPayReturnDomain.setMerchantAccount(anRes.getMerchant());

                nocardPayReturnDomain.setYbOrderId(anRes.getoTradeNum());
                noCardIncomeService.notifyOrder(nocardPayReturnDomain);
    		} catch (Exception e) {
    			log.error(e);
    			return "fail";
    		}
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
        }
        return "SUCCESS";
    }
}
